package com.nmgs;

import com.nmgs.util.FileUtil;
import com.nmgs.util.PathUtil;
import com.nmgs.util.PropertiesUtil;
import com.nmgs.util.sql.SqlUtil;
import com.trkf.PasswordEncryption.PassWordUtils;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertiesPropertySource;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;

@Configuration
public class MyEnvironmentPostProcessor implements EnvironmentPostProcessor {

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment configurableEnvironment, SpringApplication application) {
        System.out.println("读取公用配置文件");
        System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
        System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
        //公用配置文件路径
        String path = PathUtil.applicationPath;
        //本项目配置文件路径
        String Newpath = PathUtil.projectApplicationPath;

        System.out.println("项目对外配置 : " + path);
        System.out.println("项目内部配置 : " + Newpath);
        Properties properties = new Properties();
        Properties Newproperties = new Properties();//项目之外的配置
        try {
            File fileproperties = new File(path);
            InputStream input = getClass().getClassLoader().getResourceAsStream("application.properties");
            // 判断文件夹是否存在
            if (!fileproperties.exists()) {
                fileproperties.createNewFile();
            }
            String logPath= PathUtil.jarPath +File.separator+ "logs/log.out";
            File logPathfile = new File(logPath);
           if (!logPathfile.exists()) {
               logPathfile.mkdirs();
            }
            Newproperties.load(Files.newInputStream(Paths.get(path)));
            properties.load(input);
            String DBType = Newproperties.getProperty("DBType") == null ? "1" : Newproperties.getProperty("DBType");
            SqlUtil.Dbtype=Integer.parseInt(DBType);
            properties.setProperty("server.port", Newproperties.getProperty("serverport"));
            properties.setProperty("spring.logback.logPath", PathUtil.jarPath +File.separator+ "logs");
            properties.setProperty("spring.datasource.url", Newproperties.getProperty("DBUrl"));
            properties.setProperty("spring.datasource.username", Newproperties.getProperty("DBUserName"));
            properties.setProperty("spring.datasource.password", PassWordUtils.decrypt(Newproperties.getProperty("DBPassWord")));
            if (DBType.equals("1")) {
                properties.setProperty("spring.datasource.driver-class-name", properties.getProperty("sqlClassName"));
                properties.setProperty("spring.datasource.validationQuery", properties.getProperty("sqlvalidationQuery"));
                properties.setProperty("spring.datasource.hikari.connection-test-query", properties.getProperty("sqlvalidationQuery"));
            } else if (DBType.equals("2")) {
                properties.setProperty("spring.datasource.driver-class-name", properties.getProperty("OracleClassName"));
                properties.setProperty("spring.datasource.validationQuery", properties.getProperty("OraclevalidationQuery"));
                properties.setProperty("spring.datasource.hikari.connection-test-query", properties.getProperty("OraclevalidationQuery"));
            } else if (DBType.equals("3")) {
                properties.setProperty("spring.datasource.driver-class-name", properties.getProperty("DMClassName"));
                properties.setProperty("spring.datasource.validationQuery", properties.getProperty("DMvalidationQuery"));
                properties.setProperty("spring.datasource.hikari.connection-test-query", properties.getProperty("DMvalidationQuery"));
                properties.setProperty("spring.jpa.properties.hibernate.dialect", "org.hibernate.dialect.DmDialect");

            } else if (DBType.equals("4")) {
                properties.setProperty("spring.datasource.driver-class-name", properties.getProperty("MySQLClassName"));
                properties.setProperty("spring.datasource.validationQuery", properties.getProperty("MySQLvalidationQuery"));
                properties.setProperty("spring.datasource.hikari.connection-test-query", properties.getProperty("MySQLvalidationQuery"));
            }
            System.out.println("---------------------------本次载入数据库----------------------");
            System.out.println("---------------------------------------------------------------------");
            System.out.println("---------------------------------------------------------------------");
            System.out.println("driver-class-name:  " + properties.getProperty("spring.datasource.driver-class-name"));
            System.out.println("       url       :  " + properties.getProperty("spring.datasource.url"));
            System.out.println("     username    :  " + properties.getProperty("spring.datasource.username"));
            //环境名称随意取，但尽量不能和其他环境名称相同，避免不生效
            PropertiesPropertySource propertySource = new PropertiesPropertySource("environmentPostProcessor", properties);
           // PropertiesPropertySource newPropertySource = new PropertiesPropertySource("newEnvironmentPostProcessor", Newproperties);
            //外部的文件是最先导入的
            configurableEnvironment.getPropertySources().addFirst(propertySource);
            //如果公用配置文件没有配置的则使用本项目的配置文件
           // configurableEnvironment.getPropertySources().addLast(newPropertySource);
           /* File file = new File(PathUtil.staticResourcesPath);
            if (!file.isDirectory()) {
                file.mkdirs();
            }*/
            //toCopyFile();
            String appName = properties.getProperty("spring.logback.appName");
            String versionPath = PathUtil.versionPath;
            File resourceDir = new File(versionPath);
            String version = getVersionFileName(resourceDir);
            String applicationTextPath=PathUtil.applicationTextPath;
            if(!"".equals(version) && version !=null){
              //  new PropertiesUtil(applicationTextPath).set(appName + "Version", version);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*private void toCopyFile() {
        String path = PathUtil.webPath + "/resource/img";
        File dir = new File(path);
        if (!dir.isDirectory()) {
            dir.mkdirs();
        }
        File[] files = dir.listFiles();
        if (files != null) {
            for (File file : files) {
                File newFile = new File(PathUtil.staticResourcesPath + "/" + file.getName());
                if (!newFile.exists()) {
                    FileUtil.copyFile(path + "/" + file.getName(), PathUtil.staticResourcesPath + "/" + file.getName());
                }
            }
        }
    }*/

    private String getVersionFileName(File dir) {
        String version = "";
        List<String> fileNames = new ArrayList<>();
        if (dir == null || !dir.exists() || !dir.isDirectory()) {
            System.out.println("获取系统版本====版本文件为空");
            return version;
        }
        File[] files = dir.listFiles();
        if (files != null) {
            System.out.println("获取系统版本===="+files.length);
            for (File file : files) {
                if (file.isFile() && file.getName().endsWith(".txt")) {
                    fileNames.add(file.getName());
                }
            }
        }
        System.out.println("获取系统版本====是否有版本文件=="+fileNames.isEmpty());
        if (!fileNames.isEmpty()) {
            version = fileNames.get(0).replace(".txt", "");
        }
        return version;
    }
}
